import { TOKEN } from "../config/cachekey"
import Cache from "./cache"
// const baseUrl = 'http://bob.jiaoguanyi.cn/'  //本地
// const baseUrl = 'https://test.jiaoguanyi.cn/'  //测试站
const baseUrl = 'https://service.jiaoguanyi.cn/'  //正式站


const request = (method, url, data, header = {}) => {
	 // 合并传入的 header 和默认的 content-type、token
	    const headersWithToken = {
	        ...header,
	        'Content-Type': 'application/json',
	        'token': `${Cache.get(TOKEN)}`
	    };
	return new Promise((resolve, reject) => {
		uni.request({
			method: method,
			url: baseUrl + url,
			data: data,
			dataType: 'json',
			header: headersWithToken,
			success: (res) => {
				if (res.data.code === 200) {
					uni.hideLoading();
					resolve(res.data)
				} else {
					uni.hideLoading();
					reject(res.data)
				}
			},
			fail: (err) => {
				uni.hideLoading();
				reject(err.data)
			}
		})
	})
}

export default function(method = 'get', url = '', data = {}) {
	method = method.toLowerCase();
	if (method == 'post') {
		return request('post', url, data)
	} else if (method == 'get') {
		return request('get', url, data)
	} else if (method == 'delete') {
		return request('delete', url, {
			params: data
		})
	} else if (method == 'put') {
		return request('put', url, data)
	} else {
		console.error('未知的method' + method)
		return false
	}
}

export function getBaseUrl() {
	return baseUrl;
}
